var bearcat = require("bearcat")

var matchHandler = function(app) {
  this.app = app;
  this.sessionService = this.app.get('sessionService')
  this.matchServer = this.app.get('matchServer')
};
//加入匹配
matchHandler.prototype.joinMatch = function(msg, session, next) {
  var uid = session.get("uid")
  if(!uid){
    next(null,{flag : false,msg : "未登录"})
    return
  }
  let gameType = msg.gameType || "default"
  this.matchServer.joinMatch(uid,gameType,function(flag,msg) {
    next(null,{flag : flag,msg : msg})
  })
}
//离开匹配
matchHandler.prototype.leaveMatch = function(msg, session, next) {
  var uid = session.get("uid")
  if(!uid){
    next(null,{flag : false,msg : "未登录"})
    return
  }
  this.matchServer.leaveMatch(uid,function(flag,msg) {
    next(null,{flag : flag,msg : msg})
  })
}
//关闭房间
matchHandler.prototype.closeRoom = function(msg, session, next) {
  var uid = session.get("uid")
  if(!uid){
    next(null,{flag : false,msg : "未登录"})
    return
  }
  this.matchServer.closeRoom(uid,function(flag,msg) {
    next(null,{flag : flag,msg : msg})
  })
}
//发送消息
matchHandler.prototype.sendMessage = function(msg, session, next) {
  var uid = session.get("uid")
  var text = msg.text
  if(!uid){
    next(null,{flag : false,msg : "未登录"})
    return
  }
  this.matchServer.sendMessage(uid,text,function(flag,msg) {
    next(null,{flag : flag,msg : msg})
  })
}
//保存房间数据
matchHandler.prototype.saveRoomData = function(msg, session, next) {
  var uid = session.get("uid")
  var key = msg.key
  var value = msg.value
  if(!uid){
    next(null,{flag : false,msg : "未登录"})
    return
  }
  this.matchServer.saveRoomData(uid,key,value,function(flag,msg) {
    next(null,{flag : flag,msg : msg})
  })
}
//获取全部房间数据
matchHandler.prototype.getRoomData = function(msg, session, next) {
  var uid = session.get("uid")
  if(!uid){
    next(null,{flag : false,msg : "未登录"})
    return
  }
  this.matchServer.getRoomData(uid,function(flag,msg) {
    next(null,{flag : flag,msg : msg})
  })
}
//房间指令
matchHandler.prototype.roomCmd = function(msg, session, next) {
  var uid = session.get("uid")
  if(!uid){
    next(null,{flag : false,msg : "未登录"})
    return
  }
  this.matchServer.roomCmd(uid,msg,function(flag,msg) {
    next(null,{flag : flag,msg : msg})
  })
}
module.exports = function(app) {
  return bearcat.getBean({
  	id : "matchHandler",
  	func : matchHandler,
  	args : [{
  		name : "app",
  		value : app
  	}],
  	props : [{
  		name : "redisDao",
  		ref : "redisDao"
  	}]
  })
};